package wypozyczalnia.spring;

import java.net.InetAddress;
import java.net.UnknownHostException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import wypozyczalnia.config.ApplicationProperties;


public class WypozyczalniaHandlerInterceptor extends HandlerInterceptorAdapter {

	private final Logger logger = Logger
			.getLogger(WypozyczalniaHandlerInterceptor.class);

	public final static String MESSAGE_KEY = "message";
	private String version = null;

	@Autowired
	private ApplicationProperties ap;

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		logger.debug("REQUEST: " + request.getRequestURI() + " -> "
				+ handler.getClass());
		HttpSession session = request.getSession(false);
		if(session!=null) {
		String currentUserName = SecurityContextHolder.getContext()
				.getAuthentication().getName();
		logger.debug("USER: "+currentUserName);
		session.setAttribute("currentUserName", currentUserName);
		}
		
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		if (modelAndView != null
				&& !modelAndView.getViewName().startsWith("redirect:")) {
			modelAndView.getModel().put("rootURL", request.getContextPath());
			modelAndView.getModel().put("appVersion", getAppVersion());
			modelAndView.getModel().put("envId", ap.getEnvironmentId());
			String viewName = modelAndView.getViewName();
			if (!viewName.equals("location") && !viewName.startsWith("reload")) {
				HttpSession session = request.getSession(false);
				if (session != null
						&& session.getAttribute(MESSAGE_KEY) != null) {
					modelAndView.getModel().put(MESSAGE_KEY,
							session.getAttribute(MESSAGE_KEY));
					session.removeAttribute(MESSAGE_KEY);
				}
			}
			response.addHeader("Cache-Control", "no-cache");
			if (modelAndView.getViewName().endsWith(".jsp")) {
				response.setHeader("Pragma", "public");
				response.setHeader("Cache-Control", "max-age=0");
			}
		}
	}

	private String getAppVersion() {
		if (version == null) {
			try {
				version = getNodeName()
						+ " :: "
						+ IOUtils.toString(getClass().getResourceAsStream(
								"/conngtwy-gui-version.txt"));
			} catch (Exception ex) {
				version = "";
			}
		}
		return version;
	}

	private String getNodeName() {
		try {
			return InetAddress.getLocalHost().getCanonicalHostName();
		} catch (UnknownHostException e) {
			return "" + System.currentTimeMillis();
		}
	}
}
